const app = getApp();
import {
  getMineInfo,
  updataUsers,
  getFollow,
  getFans,
  updateCredits,
  getUserById,
  getArchive,
  getCredit,
  getFavPosts,
  getLikePosts
} from "../api/user";

import {
  uploadMedia,
} from "../api/common.js";


/**
 * 获取用户信息
 */
const getUserMineInfo = function () {
  let that = this;
  getMineInfo().then(res => {
      console.log(res)
      this.setData({
        user: res.user,
        social: res.social,
        credit: res.credit,
        account: res.account,
        honour: res.honour,
        board_id:res.board_id,
        imagesubject: res.user.background,
        avatar: res.user.avatarUrl,
        nickName: res.user.nickName,
        signature: res.user.description,
        gender: res.user.gender,
        birth: res.user.birthday
      })
    })
    .catch(err => {
      console.log(err)
      if (err.message == "无效授权登录信息,或授权登录已过期") {
        that.data.currentConfig.show = true;
        that.setData({
          currentConfig: that.data.currentConfig,
        })
      }
    })
}

const updataUser = function (e) {
  let args = {
    background: this.data.imagesubject,
    description: this.data.signature,
    birthday: this.data.birth,
    nickname: this.data.nickName,
    avatar:this.data.avatar,
  }
  updataUsers(args).then(res => {
    console.log(args);
    console.log(res);
    wx.setStorageSync('user', res.user);
    if (res.access_token) {
      wx.showToast({
        title: '用户信息更新成功',
      })
      wx.setStorageSync('token', res.access_token);
      wx.setStorageSync('expired_in', Date.now() + parseInt(res.expired_in, 10) * 100000 - 60000);
      wx.navigateBack({

      })
    }
  })

}


const addAvatar = function () {
  let that=this;
  wx.chooseImage({
    count: 1,
    success: function (res) {
      wx.showLoading({
        title: '图片上传中',
      })
      let file = res.tempFilePaths[0];
      uploadMedia(file).then(res => {
        if (res.url) {
          wx.hideLoading();
          that.setData({
            avatar: res.url
          })
        }

      }).catch(err => {
        console.log(err)
        if (err.message == "未授权登录用户,不能上传") {
          that.data.currentConfig.show = true;
          that.setData({
            currentConfig: that.data.currentConfig,
          })
        }

        wx.showToast({
          title: '图片添加失败'
        })
      })
    }
  })
}

/**
 * 获取用户关注
 */

const getUserFollow = function (id, page) {
  var that = this;
  let args = {};
  getFollow(id, page).then(res => {
      console.log(res)
      if (res.length <= 10) {
        this.setData({
          isLastPage: true,
          loadtext: '到底啦',
        })
      }
      if (this.data.bottom) {
        args.page = this.data.page + 1
        args.followlist = [].concat(this.data.followlist, res)
      } else {
        args.page = this.data.page + 1;
        args.followlist = res;
      }
      that.setData(args);
    })
    .catch(err => {
      console.log(err)
    })
}


const getUserFans = function (id, page) {
  var that = this;
  let args = {};
  getFans(id, page).then(res => {
      console.log(res)
      if (res.length < 10) {
        this.setData({
          isLastPage: true,
          loadtext: '到底啦',
        })
      }
      if (this.data.bottom) {
        args.page = this.data.page + 1
        args.followlist = [].concat(this.data.followlist, res)
      } else {
        args.page = this.data.page + 1;
        args.followlist = res;
      }
      that.setData(args);
    })
    .catch(err => {
      console.log(err)
    })
}


const tapSubscribe = function () {
  let templates = app.globalData.templates.subscribe
  wx.requestSubscribeMessage({
    tmplIds: templates,
    success(res) {
      console.log(res)
      let template_id = JSON.stringify(res)
      for (let i = 0; i < templates.length; i++) {
        let template = templates[i]
        let response = template_id.replace(template, "status")
        let subscribe = JSON.parse(response)
        //console.log(result)
        app.vPush.addFormId(template, subscribe.status)
      }
      if (res.errMsg == "requestSubscribeMessage:ok") {
        wx.showToast({
          // title: '订阅消息完成',
          icon: 'success',
          duration: 1000
        })
      }
    },
    fail: function (res) {
      console.log(res);
    }
  })
}

const sign = function (e) {
  var id = e.currentTarget.id;
  this.setData({
    isSignInDialog: false,
  })
  this.updateCredit('sign', this.data.user.userId, true);
}


const updateCredit = function (action, uid, show) {
  updateCredits({
    action: action,
    uid: uid
  }).then(res => {
    console.log(res);
    if (show) {
      this.data.credit.is_sign=true,
      this.data.credit.days = this.data.credit.days + 1;
      this.setData({
        visible: true,
        credits: res.credits,
        credit: this.data.credit
      })
      wx.showToast({
        title: res.message,
      })
    }
    if(res.status==403){
      wx.showToast({
        title: '超过限制次数',
      })
    }
  }) .catch(err => {
    wx.showToast({
      title: err.message,
    })
  })
}

const getUserinfoById = function (id) {
  getUserById(id).then(res => {
      console.log(res)
      // wx.setStorageSync('user', res)
      this.setData({
        userInfo: res,
        isFollow: res.status,
      })
    })
    .catch(err => {
      console.log(err)
    })
}

const getachire = function () {
  getArchive().then(res => {
    console.log(res);
    this.setData({
      archive: res.data,
    })
  })
}

const getCreditList = function (data) {
  getCredit(data).then(res => {
      let args = {}
      args.showloading = false;
      if (res.length == 0) {
        L
        this.setData({
          nodate: true
        })
      }
      if (res.length < 10) {
        this.setData({
          nodata: true,
          showloadmore: false,
          isLastPage: true,
          loadtext: '到底啦'
        })
      }
      if (this.data.isBottom) {
        args.creditlist = [].concat(this.data.creditlist, res)
        args.page = this.data.page + 1
      } else {
        args.creditlist = res
        args.page = this.data.page + 1
      }
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
      this.setData({
        isMessage: true
      })
      wx.stopPullDownRefresh()
    })

}

const getUserFavPosts = function (args) {
  let that = this;
  getFavPosts(args).then(res => {
      let args = {}
      if (res.length < 10) {
        this.setData({
          isLastPage: true,
          loadtext: '到底啦'
        })
      }
      if (res.error != "no posts found") {
        let n = Math.floor(Math.random() * res.length)
        args.cover = res[n].meta.thumbnail
        this.setData(args)
      } else {}
      if (this.data.isPull) {
        this.setData({
          isPull: false
        })
        wx.stopPullDownRefresh()
      } else if (this.data.isBottom) {
        args.posts = [].concat(this.data.posts, res)
        args.page = this.data.page + 1
      } else {
        args.posts = res;
        args.page = this.data.page + 1
      }
      this.setData(args);
      wx.hideLoading()
    })
    .catch(err => {
      if (err.message = "授权信息有误") {
        that.setData({
          showlogin: true,
          nologin: true
        })
      }
    })
}


const getUserLikePosts = function (args) {
  let that = this;
  getLikePosts(args).then(res => {
      let args = {}
      if (res.length < 10) {
        this.setData({
          isLastPage: true,
          loadtext: '到底啦'
        })
      }
      if (res.error != "no posts found") {
        let n = Math.floor(Math.random() * res.length)
        args.cover = res[n].meta.thumbnail
        this.setData(args)
      } else {}
      if (this.data.isPull) {
        this.setData({
          isPull: false
        })
        wx.stopPullDownRefresh()
      } else if (this.data.isBottom) {
        args.posts = [].concat(this.data.posts, res)
        args.page = this.data.page + 1
      } else {
        args.posts = res;
        args.page = this.data.page + 1
      }
      this.setData(args);
      wx.hideLoading()
    })
    .catch(err => {
      if (err.message = "授权信息有误") {
        that.setData({
          showlogin: true,
          nologin: true
        })
      }
    })
}



module.exports = function (obj) {
  obj.getUserMineInfo = getUserMineInfo;
  obj.updataUser = updataUser;
  obj.getUserFollow = getUserFollow;
  obj.getUserFans = getUserFans;
  obj.tapSubscribe = tapSubscribe;
  obj.sign = sign;
  obj.updateCredit = updateCredit;
  obj.getUserinfoById = getUserinfoById;
  obj.getachire = getachire;
  obj.getCreditList = getCreditList;
  obj.getUserFavPosts = getUserFavPosts;
  obj.getUserLikePosts = getUserLikePosts;
  obj.addAvatar=addAvatar;
  
}